package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.UserExceptionConstant;
import com.itheima.domain.PageBean;
import com.itheima.domain.dto.UserEditDTO;
import com.itheima.domain.dto.UserPageDTO;
import com.itheima.domain.po.User;
import com.itheima.exception.UserException;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import com.itheima.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(String username, String password) {

        User user = new User();
        user.setUsername(username);

        User Find_User = userMapper.find(user);

        if (Find_User != null) {
           throw new UserException(UserExceptionConstant.USER_HAVE_REGISTER);
        }

        String md5String = Md5Util.getMD5String(password);

        int row = userMapper.register(username, md5String);

        if (row != 1) {
            throw new UserException(UserExceptionConstant.USER_REGISTER_ERR);
        }



    }


    @Override
    public User userLogin(String username, String password) {

        User user = new User();

        user.setUsername(username);
        user.setPassword(Md5Util.getMD5String(password));


        User Find_User = userMapper.find(user);

        if (Find_User == null) {
            throw new UserException(UserExceptionConstant.USER_NOT_FIND);
        }


        if (!Md5Util.checkPassword(password,Find_User.getPassword())) {
            throw new UserException(UserExceptionConstant.USER_PASSWORD_ERROR);
        }

        return Find_User;

    }


    @Override
    public void Edit(UserEditDTO userEditDTO) {


        int row = userMapper.Edit(userEditDTO);


        if (row != 1) {
            throw new UserException(UserExceptionConstant.USER_UPDATE_ERROR);
        }
    }


    @Override
    public PageBean<User> list(UserPageDTO userPageDTO) {

        PageBean<User> pb_user = new PageBean<>();

        PageHelper.startPage(userPageDTO.getPageNum(),userPageDTO.getPageSize());


        List<User> userList = userMapper.list(userPageDTO);


        Page<User> data = (Page<User>) userList;

        pb_user.setTotal(data.getTotal());
        pb_user.setItems(data.getResult());

        return pb_user;
    }
}
